<template>
  <div class="meter-selector">
    <el-button type="primary" @click="dialogVisible = true">
      <template #icon>
        <el-icon>
          <Filter />
        </el-icon>
      </template>
      {{
        meterStore.currentMeter ? meterStore.currentMeter.meter_code : "全部"
      }}
    </el-button>

    <el-dialog v-model="dialogVisible" :title="'当前表计:' +
      (meterStore.currentMeter ? meterStore.currentMeter.meter_code : '全部')
      " width="600px">
      <div class="meter-selector__content">
        <!-- 添加全部选项 -->
        <div class="select-all-option">
          <el-radio-group v-model="selectedType" @change="handleSelectAll">
            <el-radio value="all" :label="'all'">全部</el-radio>
            <el-radio value="specific" :label="'specific'">选择具体表计</el-radio>
          </el-radio-group>
        </div>

        <!-- 树形选择器 -->
        <el-scrollbar height="400px">
          <MeterTree :data="meterStore.treeDataForChart" :disabled="selectedType === 'all'"></MeterTree>
        </el-scrollbar>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { Filter } from "@element-plus/icons-vue";
import MeterTree from "@/components/meter/MeterTree.vue";
import { useMeterStore } from "@/stores/meter";

const meterStore = useMeterStore();
const dialogVisible = ref(false);
const selectedType = ref(meterStore.currentMeter ? "specific" : "all");

const props = defineProps({
  type: {
    type: Number,
    default: 1,
  },
});

// 处理全部选项的选择
const handleSelectAll = (value) => {
  if (value === "all") {
    meterStore.setCurrentMeter(null);
  }
};

// 确认按钮处理
const handleConfirm = () => {
  if (selectedType.value === "all") {
    meterStore.setCurrentMeter(null);
  }
  dialogVisible.value = false;
};

// 监听当前表计变化，更新选择类型
watch(
  () => meterStore.currentMeter,
  (newVal) => {
    selectedType.value = newVal ? "specific" : "all";
  }
);

</script>

<style scoped>
.meter-selector__content {
  padding: 10px;
}

.select-all-option {
  margin-bottom: 15px;
  padding: 10px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.meter-selector__search {
  margin-bottom: 15px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.meter-code {
  color: #999;
  font-size: 12px;
}
</style>
